import axios from "axios";
import dayjs from "dayjs";
import router from "@/router";

function validateJWT(token) {
  let result = true;
  const match = token?.match(/\.(\w+)\./);
  if (match && match[1]) {
    const { exp } = JSON.parse(window.atob(match[1]));
    if (exp - dayjs().unix() < 5) {
      result = false;
    }
  }
  return result;
}

const request = axios.create({
  baseURL: import.meta.env.VITE_APP_API_URL,
});

request.interceptors.request.use((config) => {
  return config;
}, Promise.reject);

request.interceptors.response.use(
  ({ data }) => {
    console.log(data)
    if (data instanceof Blob) {
      return Promise.resolve(data);
    } else if (data.status === 200) {
      return Promise.resolve(data.result);
    } else {
      return Promise.reject(data.message);
    }
  },
  (err) => {
    if (err === "tokenExpired") {
      router.push("/login");
      return Promise.reject("登陆已过期,请重新登陆");
    } else {
      return Promise.reject("请求异常");
    }
  }
);

export default request;
